document.addEventListener("DOMContentLoaded", function () {
    // 检查本地存储中是否存在username和token
    var username = localStorage.getItem('username');
    var token = localStorage.getItem('token');
    // 如果username和token存在，重定向用户到主页
    if (username && token) {
        window.location.href = "/";
    }
    const loginForm = document.querySelector(".login-form");

    loginForm.addEventListener("submit", function (event) {
        event.preventDefault(); // 阻止表单默认提交行为

        // 获取用户输入的数据
        const mail = document.querySelector("input[type='text']").value;  // 注意这里的选择器可能需要根据实际的HTML结构进行修改
        const password = document.querySelector("input[type='password']").value;

        // 构建请求体
        const loginData = {
            mail: mail,
            password: password
        };

        // 发送AJAX请求到后端
        fetch("/api/login", {
            method: "POST",
            headers: {
                "Content-Type": "application/json"
            },
            body: JSON.stringify(loginData)
        })
            .then(response => response.json())
            .then(data => {
                if (data.data.code === 200) {
                    // 登录成功处理
                    localStorage.setItem("token", data.data.token); // 将token保存到浏览器的localStorage
                    localStorage.setItem("username", data.data.username); // 将username保存到浏览器的localStorage
                    document.cookie = `username=${data.data.username}; path=/`;
                    document.cookie = `token=${data.data.token}; path=/`;
                    window.location.href = "/";

                    // 调用 /api/set_token
                    fetch('/api/set_token', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'Authorization': 'Bearer ' + data.data.token  // 假设token是用于授权的
                        },
                        body: JSON.stringify({
                            username: data.data.username,
                            token: data.data.token
                        })
                    })
                        .then(response => response.json())
                        .then(data => {
                            console.log('Token设置成功');
                        })
                        .catch(error => console.error('错误:', error));
                } else {
                    // 登录失败处理
                    alert("邮箱或密码错误，请重新输入！");
                }
            })
            .catch(error => {
                console.error("登录请求失败", error);
                alert("登录过程中发生错误，请稍后再试！");
            });
    });
});
document.querySelector('.login-form').addEventListener('submit', function (event) {
    event.preventDefault();

    var username = document.querySelector('input[type="text"]').value;
    var password = document.querySelector('input[type="password"]').value;

    fetch('/api/login', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            username: username,
            password: password
        })
    })
        .then(response => response.json())
        .then(data => {
            if (data.data.code === 200) {
                localStorage.setItem('token', data.data.token);
                localStorage.setItem('username', username);
                document.cookie = `username=${username}; path=/`;
                document.cookie = `token=${data.data.token}; path=/`;

                window.location.href = "/";

                // 调用 /api/set_token
                fetch('/api/set_token', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': 'Bearer ' + data.data.token  // 假设token是用于授权的
                    },
                    body: JSON.stringify({
                        username: username,
                        token: data.data.token
                    })
                })
                    .then(response => response.json())
                    .then(data => {
                        console.log('Token设置成功');
                    })
                    .catch(error => console.error('错误:', error));
            } else {
                console.log('登录失败');
            }
        })
        .catch(error => console.error('错误:', error));
});
